/*
 * @Author: your name
 * @Date: 2020-12-02 15:26:00
 * @LastEditTime: 2020-12-18 15:46:11
 * @LastEditors: your name
 * @Description: In User Settings Edit
 * @FilePath: \nuxt模板-实现国际化\store\user.js
 */
import { login, getInfo, logout } from '~/assets/api/user'
import { setToken, removeToken } from '~/assets/util/auth'
function getDefault() {
  return {
    nickname: '',
    token: '',
  }
}

export const state = () => getDefault()

export const mutations = {
  SET_TOKEN(state, token) {
    state.token = token
  },
  SET_INFO(state, info) {
    state = Object.assign(state, info, { token: state.token })
  },
  RESET(state) {
    state = getDefault()
  },
}

export const actions = {
  async login({ commit }, param) {
    const { data } = await login(param)
    if (data) {
      commit('SET_TOKEN', data.token)
      setToken(data.token)
      return true
    } else {
      return false
    }
  },

  async getInfo({ commit }) {
    const { data } = await getInfo()
    if (data) {
      commit('SET_INFO', data.info)
    }
  },

  async logout({ commit }) {
    const { error } = await logout()
    if (error) {
      removeToken()
    }
  },
}
